package util;

import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class MailUtil {

    public static void enviarEmail(String remetente, String destinatario, String assunto, String mensagem) throws MessagingException {

        Session session = Session.getInstance(getProps(), getAuth());

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(remetente));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(destinatario));
        message.setSubject(assunto);
        message.setContent(mensagem, "text/html");

        Transport.send(message);

        session = null;

    }

    public static Authenticator getAuth() {
        return new javax.mail.Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(ConsUtil.AUTO_EMAIL, ConsUtil.AUTO_EMAIL_SENHA);
            }
        };
    }

    public static Properties getProps() {

        Properties props = new Properties();

        props.put("mail.smtp.host", "smtp.gmail.com"); //SMTP
        props.put("mail.smtp.socketFactory.port", "465"); //PORTA SMTP
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); //Define a conexão do tipo SSL
        props.put("mail.smtp.auth", "true"); //DEFINE AUTENTICAÇÃO NECESSÁRIA
        props.put("mail.smtp.port", "465"); //PORTAL LOCAL SMTP

        return props;
    }
}
